using RealtimeCollabGame.Application.Commands;
using RealtimeCollabGame.Application.Interfaces;
using RealtimeCollabGame.Domain.Entities;

namespace RealtimeCollabGame.Application.Handlers;

public class CreateGameCommandHandler
{
    private readonly IGameRepository _gameRepository;
    private readonly IPlayerRepository _playerRepository;

    public CreateGameCommandHandler(IGameRepository gameRepository, IPlayerRepository playerRepository)
    {
        _gameRepository = gameRepository;
        _playerRepository = playerRepository;
    }

    public async Task<Game> HandleAsync(CreateGameCommand command)
    {
        // 检查房间代码是否已存在
        if (await _gameRepository.ExistsByCodeAsync(command.Code))
        {
            throw new InvalidOperationException($"房间代码 {command.Code} 已存在");
        }

        var game = new Game(
            command.Name,
            command.Code,
            command.MaxPlayers,
            command.GameDuration,
            command.Password
        );

        // 创建游戏
        game = await _gameRepository.AddAsync(game);

        // 创建创建者玩家并添加到游戏
        var creator = new Player(command.CreatorNickName);
        creator = await _playerRepository.AddAsync(creator);
        game.AddPlayer(creator);

        // 保存更新后的游戏
        await _gameRepository.UpdateAsync(game);

        return game;
    }
} 